from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import login_required
from app.models import MonitorPoint, AlarmRule, AlarmRecord
from app import db
from datetime import datetime

bp = Blueprint('alarm', __name__, url_prefix='/alarm')

@bp.route('/')
@login_required
def index():
    # 获取活跃的报警记录
    active_alarms = AlarmRecord.query.filter_by(status='active')\
        .order_by(AlarmRecord.created_at.desc()).all()
    
    # 获取已解决的报警记录
    resolved_alarms = AlarmRecord.query.filter_by(status='resolved')\
        .order_by(AlarmRecord.resolved_at.desc()).limit(50).all()
    
    return render_template('alarm/index.html',
                         active_alarms=active_alarms,
                         resolved_alarms=resolved_alarms)

@bp.route('/rules')
@login_required
def rules():
    points = MonitorPoint.query.all()
    rules = AlarmRule.query.order_by(AlarmRule.point_id, AlarmRule.parameter).all()
    return render_template('alarm/rules.html', points=points, rules=rules)

@bp.route('/rules/add', methods=['GET', 'POST'])
@login_required
def add_rule():
    if request.method == 'POST':
        rule = AlarmRule(
            point_id=request.form.get('point_id', type=int),
            parameter=request.form.get('parameter'),
            min_value=request.form.get('min_value', type=float),
            max_value=request.form.get('max_value', type=float),
            level=request.form.get('level'),
            enabled=True
        )
        db.session.add(rule)
        db.session.commit()
        flash('报警规则添加成功', 'success')
        return redirect(url_for('alarm.rules'))
    
    points = MonitorPoint.query.all()
    return render_template('alarm/add_rule.html', points=points)

@bp.route('/rules/<int:rule_id>/toggle', methods=['POST'])
@login_required
def toggle_rule(rule_id):
    rule = AlarmRule.query.get_or_404(rule_id)
    rule.enabled = not rule.enabled
    db.session.commit()
    flash(f'报警规则已{"启用" if rule.enabled else "禁用"}', 'success')
    return redirect(url_for('alarm.rules'))

@bp.route('/resolve/<int:alarm_id>', methods=['POST'])
@login_required
def resolve_alarm(alarm_id):
    alarm = AlarmRecord.query.get_or_404(alarm_id)
    alarm.status = 'resolved'
    alarm.resolved_at = datetime.utcnow()
    db.session.commit()
    flash('报警已处理', 'success')
    return redirect(url_for('alarm.index')) 